﻿using Domain.Event;
using Domain.IRepositorys;
using Domain.Model;
using Domain.Services;
using Infrastructure.DomainEvent;
using Infrastructure.UniOfWorkBase;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Utility;

namespace Application.Event
{
    /// <summary>
    /// 用户注册事件
    /// </summary>
    public class UserRegisterEventHandler : IDomainEventHandler<UserRegisterEvent>
    {
        public IWalletRepository walletRepository { get; set; }
        public IUserRepository userRepository { get; set; }
        public IInviteLogRepository inviteLogRepository { get; set; }
        public IEFUnitOfWork efUnitOfWork { get; set; }
        public IMService iMService { get; set; }
        public override Task HandleAysnc(UserRegisterEvent domainEvent, CancellationToken cancellationToken = default)
        {
            var user = userRepository.Entities.FirstOrDefault(i => i.Phone == domainEvent.Phone);

            UserInfoAggregate superorUser = userRepository.Entities.First(i => i.InviteCode == domainEvent.SuperorCode);

            InviteLogAggregate inviteLog = new InviteLogAggregate();

            inviteLog.Phone = domainEvent.Phone;
            inviteLog.SuperorCode = domainEvent.SuperorCode;
            inviteLog.UserID = user.ID;
            inviteLog.SuperorID = superorUser.ID;

            inviteLogRepository.Insert(inviteLog);

            WalletAggregate wallet = new WalletAggregate();
            wallet.UserID = user.ID;
            walletRepository.Insert(wallet);

            //升级任务达人等级
            user.UserLevel = Domain.Types.UserLevel.任务达人;
            user.UserLevelLogs.Add(new UserLevelLog()
            {
                OutTime = DateTime.Today.AddDays(16),
                PayMoney = 0,
                PayID = 0,
                CT = DateTime.Now,
                UT = DateTime.Now,
                Time = 0,
                UserLevel = Domain.Types.UserLevel.任务达人,
                Remark = "系统赠送15天"
            });


            efUnitOfWork.Commit();


            iMService.CreateIMUser(user);


            return Task.CompletedTask;
        }
    }
}
